<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 参数分组标签页 -->
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane v-for="group in groupList" :key="group" :label="group" :name="group"></el-tab-pane>
        <el-tab-pane v-if="showAllTab" label="全部" name="all"></el-tab-pane>
      </el-tabs>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-2">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Back" @click="backToList">返回列表</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache" v-hasPermi="['system:config:refreshCache']">刷新缓存</el-button>
        </el-col>
      </el-row>

      <!-- 参数列表 -->
      <el-table v-loading="loading" :data="configList" :row-class-name="tableRowClassName">
        <el-table-column type="index" width="55" label="#" align="center" />
        <el-table-column label="参数名称" align="center" prop="name" />
        <el-table-column label="参数键名" align="center" prop="key" :show-overflow-tooltip="true" />
        <el-table-column label="参数值" align="center" width="300">
          <!-- 根据参数类型显示不同的表单控件 -->
          <template #default="scope">
            <!-- 字符串类型 -->
            <el-input 
              v-if="scope.row.type === 'string'" 
              v-model="scope.row.value" 
              :disabled="!scope.row.editable"
              :placeholder="scope.row.editable ? '请输入参数值' : ''"
              @change="handleValueChange(scope.row)"
            />
            
            <!-- 数字类型 -->
            <el-input-number 
              v-else-if="scope.row.type === 'number'" 
              v-model="scope.row.valueNum" 
              :disabled="!scope.row.editable"
              :controls="true"
              style="width: 100%"
              @change="handleNumberChange(scope.row)"
            />
            
            <!-- 布尔类型 -->
            <el-switch 
              v-else-if="scope.row.type === 'boolean'" 
              v-model="scope.row.valueBool" 
              :disabled="!scope.row.editable"
              @change="handleBooleanChange(scope.row)"
            />
            
            <!-- JSON类型 -->
            <div v-else-if="scope.row.type === 'json'" class="json-editor-container">
              <el-button 
                size="small" 
                type="primary" 
                :disabled="!scope.row.editable"
                @click="openJsonEditor(scope.row)"
              >
                编辑JSON
              </el-button>
              <div class="json-preview" v-if="scope.row.value">
                {{ getJsonPreview(scope.row.value) }}
              </div>
            </div>
            
            <!-- 其他类型 -->
            <el-input 
              v-else 
              v-model="scope.row.value" 
              :disabled="!scope.row.editable"
              placeholder="请输入参数值"
              @change="handleValueChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="参数类型" align="center" prop="type" width="100">
          <template #default="scope">
            <dict-tag :options="typeOptions" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button 
              v-if="!scope.row.editable"
              link type="primary" 
              icon="Edit" 
              @click="handleEdit(scope.row)" 
              v-hasPermi="['system:config:edit']"
            >编辑</el-button>
            <template v-else>
              <el-button 
                link type="success" 
                icon="Check" 
                @click="handleSave(scope.row)" 
                v-hasPermi="['system:config:edit']"
              >保存</el-button>
              <el-button 
                link type="info" 
                icon="Close" 
                @click="handleCancel(scope.row)" 
                v-hasPermi="['system:config:edit']"
              >取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- JSON编辑器对话框 -->
    <el-dialog title="编辑JSON参数" v-model="jsonDialog.open" width="800px" append-to-body>
      <div class="json-editor">
        <el-input
          v-model="jsonDialog.value"
          type="textarea"
          :rows="15"
          placeholder="请输入JSON格式的参数值"
        />
      </div>
      <div class="dialog-footer" style="margin-top: 15px;">
        <el-button type="primary" @click="validateAndSaveJson">确 定</el-button>
        <el-button @click="jsonDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConfigList, getConfigGroups, getConfigDetail, updateConfig, refreshConfigCache } from '@/api/config'
import { parseConfigValue } from '@/utils/config'
import { useRouter } from 'vue-router'

const router = useRouter()

// 查询参数
const queryParams = ref({
  page: 1,
  limit: 100, // 使用大一些的分页，便于显示
  group: '',
  type: ''
})

// 列表数据
const configList = ref([])
const originalConfigList = ref([]) // 保存原始数据，用于取消编辑
const total = ref(0)
const loading = ref(false)
const activeTab = ref('')
const groupList = ref([])
const showAllTab = ref(true)
const typeOptions = ref([])

// JSON编辑器对话框
const jsonDialog = reactive({
  open: false,
  value: '',
  row: null
})

// 获取参数分组列表
const getGroups = async () => {
  try {
    loading.value = true
    const res = await getConfigGroups()
    groupList.value = res.data || []
    loading.value = false
    
    // 默认选中第一个分组
    if (groupList.value.length > 0 && !activeTab.value) {
      activeTab.value = groupList.value[0]
      queryParams.value.group = activeTab.value
      getList()
    }
  } catch (error) {
    loading.value = false
    console.error('获取参数分组失败', error)
  }
}

// 切换标签页
const handleTabClick = () => {
  if (activeTab.value === 'all') {
    queryParams.value.group = ''
  } else {
    queryParams.value.group = activeTab.value
  }
  queryParams.value.page = 1
  getList()
}

// 查询参数列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getConfigList(queryParams.value)
    // 添加编辑状态和备份原始值
    const list = res.data.list.map(item => {
      // 根据类型处理特定值
      if (item.type === 'number') {
        item.valueNum = parseFloat(item.value) || 0
      } else if (item.type === 'boolean') {
        item.valueBool = item.value === 'true' || item.value === '1'
      }
      return {
        ...item,
        editable: false,
        originalValue: item.value,
        originalValueNum: item.type === 'number' ? (parseFloat(item.value) || 0) : 0,
        originalValueBool: item.type === 'boolean' ? (item.value === 'true' || item.value === '1') : false
      }
    })
    configList.value = list
    originalConfigList.value = JSON.parse(JSON.stringify(list)) // 深拷贝
    total.value = res.data.total
  } catch (error) {
    console.error('获取参数列表失败', error)
  } finally {
    loading.value = false
  }
}

// 启用编辑模式
const handleEdit = (row) => {
  row.editable = true
}

// 取消编辑
const handleCancel = (row) => {
  // 恢复原始值
  const original = originalConfigList.value.find(item => item.id === row.id)
  if (original) {
    row.value = original.value
    row.valueNum = original.valueNum
    row.valueBool = original.valueBool
  }
  row.editable = false
}

// 保存编辑
const handleSave = async (row) => {
  try {
    // 根据类型验证参数值
    if (row.type === 'json') {
      try {
        JSON.parse(row.value)
      } catch (e) {
        ElMessage.error('JSON格式不正确，请检查')
        return
      }
    }
    
    await updateConfig(row.id, row)
    
    // 更新原始数据
    const index = originalConfigList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      originalConfigList.value[index] = JSON.parse(JSON.stringify(row))
    }
    
    row.editable = false
    ElMessage.success('修改成功')
    
    // 刷新缓存
    refreshConfigCache().catch(error => {
      console.error('刷新缓存失败', error)
    })
  } catch (error) {
    console.error('保存参数失败', error)
  }
}

// 返回列表页面
const backToList = () => {
  router.push('/system/config')
}

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    await refreshConfigCache()
    ElMessage.success('刷新缓存成功')
  } catch (error) {
    console.error('刷新缓存失败', error)
  }
}

// 处理文本值变更
const handleValueChange = (row) => {
  // 对于某些需要立即保存的场景可以在这里处理
}

// 处理数值变更
const handleNumberChange = (row) => {
  row.value = row.valueNum.toString()
}

// 处理布尔值变更
const handleBooleanChange = (row) => {
  row.value = row.valueBool.toString()
}

// 打开JSON编辑器
const openJsonEditor = (row) => {
  jsonDialog.row = row
  jsonDialog.value = row.value
  
  // 尝试格式化JSON
  try {
    const jsonObj = JSON.parse(row.value)
    jsonDialog.value = JSON.stringify(jsonObj, null, 2)
  } catch (e) {
    // 不是有效的JSON，保持原样
  }
  
  jsonDialog.open = true
}

// 验证并保存JSON
const validateAndSaveJson = () => {
  try {
    // 验证JSON格式
    const jsonObj = JSON.parse(jsonDialog.value)
    
    // 保存格式化后的JSON
    jsonDialog.row.value = JSON.stringify(jsonObj)
    
    jsonDialog.open = false
    ElMessage.success('JSON已更新，请点击保存按钮保存更改')
  } catch (e) {
    ElMessage.error('JSON格式不正确，请检查')
  }
}

// 获取JSON预览
const getJsonPreview = (json) => {
  try {
    const obj = JSON.parse(json)
    // 简化预览，最多显示3个字段
    const preview = JSON.stringify(obj).substring(0, 100)
    return preview.length < 100 ? preview : preview + '...'
  } catch (e) {
    return json.substring(0, 100) + (json.length > 100 ? '...' : '')
  }
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  return row.editable ? 'editing-row' : ''
}

onMounted(() => {
  getGroups()
})
</script>

<style scoped>
.json-editor-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.json-preview {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
  word-break: break-all;
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

:deep(.editing-row) {
  background-color: #f8f8f9 !important;
}

.el-tabs__item {
  height: 40px;
  line-height: 40px;
}
</style> 